#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
主题:合并多个字典或映射
问题: 现在有多个字典或者映射，你想将它们从逻辑上合并为一个单一的映射后执行某些操作， 比如查找值或者检查某些键是否存在。
提示 : 
"""
from collections import ChainMap


def recipe1():
    """非常简单的解决方案"""

    a = {'x': 1, 'z': 3}
    b = {'y': 2, 'z': 4}

    c = ChainMap(a, b)
    print(f"{c = }")
    print(f"{c['x'] = }")
    print(f"{c['y'] = }")
    print(f"{c['z'] = }")

    # ChainMap 类只是在内部创建了一个容纳这些字典的列表 并重新定义了一些常见的字典操作来遍历这个列表
    print(f"{len(c) = }")
    print(f"{list(c.keys()) = }")
    print(f"{list(c.values()) = }")

    # 对于字典的更新或删除操作总是影响的是列表中第一个字典
    c['z'] = 10
    c['w'] = 40
    del c['x']
    print(f"{a = }")

    # del c['y'] KeyError: "Key not found in the first mapping: 'y'"


def recipe2():
    """ChainMap 对于编程语言中的作用范围变量"""
    values = ChainMap()
    values['x'] = 1

    # Add a new mapping
    values = values.new_child()
    values['x'] = 2

    # Add a new mapping
    values = values.new_child()
    values['x'] = 3

    print(f"{values = }")
    print(f"{values['x'] = }")

    # Discard last mapping
    values = values.parents
    print(f"{values['x'] = }")

    # Discard last mapping
    values = values.parents
    print(f"{values['x'] = }")

    print(f"{values = }")


def recipe3():
    """update() 方法将两个字典合并"""

    a = {'x': 1, 'z': 3}
    b = {'y': 2, 'z': 4}

    merged = dict(b)
    merged.update(a)
    print(f"{merged['x'] = }")
    print(f"{merged['y'] = }")
    print(f"{merged['z'] = }")

    # 如果原字典做了更新，这种改变不会反应到新的合并字典中去
    a['x'] = 42
    print(f"{merged['x'] = }")
    
def main():
    print('recipe1'.center(20, '*'))
    recipe1()
    print('recipe2'.center(20, '*'))
    recipe2()
    print('recipe3'.center(20, '*'))
    recipe3()


if __name__ == '__main__':
    main()
